﻿using MediatR;
using Process.Api.Application.Command;
using Process.BLL;
using Process.ErrorCod;
using Process.Infastructure;
using Process.Model;

namespace Process.Api.Application.Handler
{
    public class GetProcessFlowListHandler : IRequestHandler<GetProcessFlowListCommand, ApiPageing<ProcessFlow>>
    {
        private readonly IProcessRepository<ProcessFlow> flowRepo;
        private readonly ILogger <GetProcessFlowListHandler> logger;

        public GetProcessFlowListHandler(IProcessRepository<ProcessFlow> flowRepo, ILogger<GetProcessFlowListHandler> logger)
        {
            this.flowRepo = flowRepo;
            this.logger = logger;
        }
        /// <summary>
        /// 获取工艺流程列表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiPageing<ProcessFlow>> Handle(GetProcessFlowListCommand request, CancellationToken cancellationToken)
        {
            ApiPageing<ProcessFlow> result = new ApiPageing<ProcessFlow>();
            var list = flowRepo.GetAllAsync().Where(x => x.IsDelete == false);

            if (!string.IsNullOrEmpty(request.FlowCode))
            {
                list = list.Where(x => x.FlowCode != null && x.FlowCode.Contains(request.FlowCode));
            }
            if (!string.IsNullOrEmpty(request.FlowName))
            {
                list = list.Where(x => x.FlowName != null && x.FlowName.Contains(request.FlowName));
            }


            var query = list.OrderByDescending(x => x.Id)
                           .Skip((request.PageIndex - 1) * request.PageSize)
                           .Take(request.PageSize)
                           .ToList();
            var total = query.Count();

            result.TotalCount = total;
            result.TotalPage = (int)Math.Ceiling((double)total / request.PageSize);
            result.Code = ErrorStatus.Success;
            result.PageData = query;
            result.Message = "获取工艺流程分页数据成功";
            return result;
        }
    }
}
